<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    const myList = [
      {
        id: 1,
        pid: 0,
        name: '张三'
      },
      {
        id: 2,
        pid: 1,
        name: '李四'
      }
      , {
        id: 3,
        pid: 2,
        name: '王五'
      },
      {
        id: 4,
        pid: 3,
        name: '老六'
      }
    ]

    // const transListToTreeData = (list, rootValue) => {
    //   const newArr = []
    //   list.forEach(({ id, pid, ...res }) => {
    //     if (pid === rootValue) {
    //       const children = transListToTreeData(list, id)
    //       children.length
    //         ? newArr.push({ id, pid, children, ...res })
    //         : newArr.push({ id, pid, ...res })
    //     }
    //   })
    //   return newArr
    // }
    const transListToTreeData = (arr, val) => {
      const newArr = {}
      arr.forEach(item => {
        if (newArr[item.pid]) {
          newArr[item.pid].push(item)
        } else {
          newArr[item.pid] = [item]
        }
      })
      // arr.forEach(item => {
      //   const children = newArr[item.id]
      //   if (children) item.children = children
      // })
      console.log(newArr)
      // return arr.filter(item => item.pid === val)
      return arr
    }


    console.log(transListToTreeData(myList, 0))
  </script>
</body>

</html>